from collections import defaultdict
import threading


class ShoppingCart:
    def __init__(self):
        self.items = defaultdict(int)  # 商品:数量

    def add_item(self, product, quantity=1):
        """线程安全的商品添加"""
        product_name = product.get("name")
        product_price = product.get("price",0)
        with threading.Lock():  # 字典非线程安全
            if product_name and product_price is not None:
                self.items[product_name] = {"price":product_price,"quantity":quantity}


    def remove_item(self, product):
        """安全移除商品"""
        return self.items.pop(product, None)

    def get_total(self):
        """计算总价（使用items视图高效遍历）"""
        print(self.items.items())
        return round(sum(item["price"] * item["quantity"] for item in self.items.values()),2)

    def apply_discount(self, discount_rules):
        """使用字典视图进行规则匹配"""
        discounted_products = discount_rules.keys() & self.items.keys()
        for product in discounted_products:
            self.items[product]["price"] *= discount_rules[product]

if __name__ == '__main__':
    cart = ShoppingCart()
    cart.add_item({"name": "Apple", "price": 100}, 3)
    cart.add_item({"name": "Banana", "price": 80}, 2)
    cart.add_item({"name": "Orange", "price": 10}, 4)
    print("Total:", cart.get_total())  # 输出总价
    cart.apply_discount({"Apple": 0.8, "Banana": 0.9})
    print("After discount:", cart.get_total())  # 输出折扣后的总价
    cart.remove_item("Orange")
    print("After removing:", cart.get_total())  # 输出移除后总价